import { Injectable } from '@nestjs/common';
import { CreateOrderDto } from './dto/create-order.dto';
import { UpdateOrderDto } from './dto/update-order.dto';
import { loadPageQueryResult } from 'src/utils/utils';
import { InjectRepository } from '@nestjs/typeorm';
import { Order } from './entities/order.entity';
import { ILike, Repository } from 'typeorm';
import { Boss } from 'src/boss/entities/boss.entity';
import { PlayWith } from 'src/play-with/entities/play-with.entity';
import { uid } from 'uid';
import { Settle } from 'src/settle/entities/settle.entity';
@Injectable()
export class OrderService {
  constructor(@InjectRepository(Order) private readonly orderRepository: Repository<Order>,//订单
    @InjectRepository(Boss) private readonly bossRepository: Repository<Boss>,//boss
    @InjectRepository(PlayWith) private readonly playWithRepository: Repository<PlayWith>,
    @InjectRepository(Settle) private readonly settleRepository: Repository<Settle>,
  ) {

  }
  //下单
  async create(createOrderDto: CreateOrderDto) {
    //先查询boss表获取boss信息
    let boss = await this.bossRepository.findOne({
      where: {
        bossId: createOrderDto.bossId
      },
    })
    //再查询playWith表获取playWith信息
    let price = 0 //总消费
    let playWithIdList = createOrderDto.playWiths
    // let playWiths = []
    let playWithList: PlayWith[] = []
    for (let i in playWithIdList) {
      let playWith = await this.playWithRepository.findOne({
        where: {
          playWithId: playWithIdList[i]
        }
      })
      playWithList.push(playWith)
      price += playWith.unitPrice * createOrderDto.orderTime
    }
    //如果余额不够就不下单
    if (boss.amount < price) {
      return {
        code: 10001,
        message: '余额不足',
      }
    }
    let obj = {
      orderId: uid(),
      bossId: createOrderDto.bossId,
      orderTime: createOrderDto.orderTime,
      playWiths: playWithList.map(item => item.playWithId).join(','),
      price: price,
      createTime: new Date().getTime(),
      bossName: boss.bossName,
      amount: boss.amount
    }
    //保存
    await this.orderRepository.save(obj)
    await this.bossRepository.update({ bossId: createOrderDto.bossId }, { amount: boss.amount - price })
    for (let i in playWithList) {
      let amount = playWithList[i].unitPrice * (100 - playWithList[i].commissionRate) / 100//当前的金额
      let settle = await this.settleRepository.findOne({ where: { playWithId: playWithList[i].playWithId } })
      let settleAmount = 0
      console.log(settle)
      if (settle && settle.playWithName) {
        settleAmount = settle.settleAmount
        //扣除抽成
        await this.settleRepository.update({ playWithId: playWithList[i].playWithId }, { settleAmount: settleAmount + amount, settleStatus: '0' })
      } else {
        await this.settleRepository.save({ playWithId: playWithList[i].playWithId, playWithName: playWithList[i].playWithName, settleAmount: amount, settleStatus: '0' })
      }
    }
    return {
      code: 1,
      message: '下单成功'
    };
  }
  //列表
  async findAll(pageNum: number, pageSize: number, bossName: string) {
    let res = await this.orderRepository.findAndCount({
      where: {
        bossName: bossName ? ILike(`%${bossName}%`) : undefined,
      },
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      order: { id: 'DESC' }
    })

    return {
      code: 1,
      data: loadPageQueryResult<[Order[], number]>(res, pageNum, pageSize)
    };
  }

  findOne(id: number) {
    return `This action returns a #${id} order`;
  }

  update(id: number, updateOrderDto: UpdateOrderDto) {
    return `This action updates a #${id} order`;
  }

  remove(id: number) {
    return `This action removes a #${id} order`;
  }
}
